package com.ok.apm.core

import android.content.Context
import java.util.concurrent.CopyOnWriteArraySet

object OkApm {

    private val mOkApmPluginSet: CopyOnWriteArraySet<IPlugin<*>> by lazy {
        CopyOnWriteArraySet()
    }

    private var mApplicationContext: Context? = null

    /**
     * okApm 初始化
     */
    @JvmStatic
    fun init(context: Context) {
        this.mApplicationContext = context.applicationContext
    }

    @JvmStatic
    fun <T : IPluginConfig> registerPlugin(plugin: (OkApm.() -> IPlugin<T>)?) {
        plugin?.invoke(this)?.let {
            mOkApmPluginSet.add(it)
        }
    }

    @JvmStatic
    fun <T : IPluginConfig> unRegisterPlugin(plugin: (() -> IPlugin<T>)?) {
        plugin?.invoke()?.let {
            with(it) {
                if (isRunning()) {
                    stop()
                    destroy()
                }
            }
            mOkApmPluginSet.remove(it)
        }
    }

    @JvmStatic
    fun <T : IPluginConfig> startPlugins(vararg plugin: IPlugin<T>) {
        plugin.forEach {
            it.start()
        }
    }

    @JvmStatic
    fun <T : IPluginConfig> stopPlugins(vararg plugin: IPlugin<T>) {
        plugin.forEach {
            it.stop()
        }
    }

    @JvmStatic
    fun startAllPlugins() {
        mOkApmPluginSet.forEach {
            it.start()
        }
    }

    @JvmStatic
    fun stopAllPlugins() {
        mOkApmPluginSet.forEach {
            it.stop()
        }
    }

    @JvmStatic
    fun <T : IPluginConfig> destroyPlugins(vararg plugin: IPlugin<T>) {
        mOkApmPluginSet.forEach {
            it.destroy()
        }
        mOkApmPluginSet.clear()
    }

    @JvmStatic
    fun destroyAllPlugins() {
        mOkApmPluginSet.forEach {
            it.destroy()
        }
        mOkApmPluginSet.clear()
    }
}

/**
 * DSL 扩展
 */
inline fun okApm(create: OkApm.() -> Unit) {
    OkApm.create()
}



